package com.jayanslow.lighting.server.dmx;

import java.util.Timer;

public class DmxController {
	public static final int FADE_DELAY = 50;
	
	private volatile DmxChannel[] channels;
	private Timer timer;
	private Serial serial;
	private boolean timerActive;
	
	//Constructor, creates all 512 channels
	public DmxController() {
		try { serial = new Serial(); }
		catch (SerialException e) { System.err.println("Serial Exception : " + e.getMessage()); }
		channels = new DmxChannel[512];
		for (short i = 0; i < 512; i++) {
			try {
				channels[i] = new DmxChannel(this, (short) (i+1));
			} catch (OverflowException e) { }
		}
		timer = new Timer();
		System.out.println("Starting Timer");
		startFades();
	}
	public void startFades() {
		if (timerActive) return;
		timerActive = true;
		timer.scheduleAtFixedRate(new Time(this), 0, FADE_DELAY);
	}
	public void stopFades() {
		if (!timerActive) return;
		timerActive = false;
		timer.cancel();
	}
	
	//Sets the 8-bit value of a channel
	public void setChannel(short c, short v) throws OverflowException {
		if (c > 512 || c < 1) throw new OverflowException("DMX Channel must be between 1 and 512");
		channels[c - 1].setValue(v);
	}
	//Gets the channel object
	public DmxChannel getChannel(short c) throws OverflowException {
		if (c > 512 || c < 1) throw new OverflowException("DMX Channel must be between 1 and 512");
		return channels[c - 1];
	}
	//Gets all channels (ID 1-512)
	public DmxChannel[] getChannels() {
		return channels;
	}
	//Get Serial object
	public Serial getSerial() {
		return serial;
	}
	public void resetChannels() {
		for (DmxChannel c : channels) c.reset();
		try { serial.sendCommand("reset"); }
		catch (SerialException e) { System.err.println("Serial Exception : " + e.getMessage()); }
	}
}